<template>
  <div class="scroll-container1">
    <div class="header" style="padding: 10px">
      <!-- <span
        class="site-icon"
        style="
          width: 60px;
          height: 60px;
          position: absolute;
          top: 5px;
          left: 30px;
          background-color: darkgrey;
        "
      ></span> -->
      <div class="site-title">中国赛宝实验室</div>
      <div class="main-title" style="width: 50vw">
        <span class="top-title">极端环境下单粒子效应远程测控平台</span>
      </div>
      <div class="weather-time-container" style="font-size: 30px">
        <span class="dateimg"></span>
        <span>{{ currentDate }}</span>
        <span>{{ currentDay }}</span>
        <span>{{ currentTime }}</span>
        <screenfull id="screenfull" class="right-menu-item hover-effect" />
      </div>
    </div>

    <!-- 设备展示与统计区域 -->
    <el-row :gutter="12" style="padding: 0px; margin: 0px">
      <el-col :span="7" style="height: 55vh" class="col-item">
        <div class="itemtitle1">系统设备展示</div>
        <!-- <div class="itemtitlebottom"></div> -->
        <BorderBox10>
          <div class="frame-jHS-3" style="padding: 2.7vh 20px 0px 0px">
            <div class="frame-JtK-11"></div>
            <div class="frame-JtK-11">
              <div class="img-AFx-1"></div>
              <div class="text-EFD-1">
                <div class="p-text-EFD-1">
                  <span class="span-glq-1">运行天数</span>
                </div>
              </div>
            </div>
            <div class="frame-JtK-11">
              <div class="img-AFx-4"></div>
              <div class="text-EFD-1">
                <div class="p-text-EFD-1">
                  <span class="span-glq-1">样品数量</span>
                </div>
              </div>
            </div>

            <div class="frame-JtK-11">
              <div class="img-AFx-2"></div>
              <div class="text-EFD-1">
                <div class="p-text-EFD-1">
                  <span class="span-glq-1">磁盘空间</span>
                </div>
              </div>
            </div>
            <div class="frame-JtK-11">
              <div class="img-AFx-3"></div>
              <div class="text-EFD-1">
                <div class="p-text-EFD-1">
                  <span class="span-glq-1">通信状态</span>
                </div>
              </div>
            </div>
          </div>

          <div
            v-for="deviceruninfo in state.deviceruninfos"
            :key="deviceruninfo"
          >
            <div class="frame-jHS-3" style="padding: 0px 20px 0px 0px">
              <div class="frame-JtK-11" style="margin: auto">
                <img
                  v-if="deviceruninfo.type == 'ic'"
                  src="@/assets/images/index/ic.png"
                  width="50px"
                  height="50px"
                  alt="ic"
                />
                <img
                  v-else-if="deviceruninfo.type == 'pd'"
                  src="@/assets/images/index/pd.png"
                  width="50px"
                  height="50px"
                  alt="pd"
                />
              </div>
              <div class="frame-JtK-11">
                <div class="text-XbU-2">
                  <div class="p-text-XbU-2">
                    <span class="span-lQH-1">{{ deviceruninfo.runDays }}</span>
                  </div>
                </div>
              </div>
              <div class="frame-JtK-11">
                <div class="text-XbU-2">
                  <div class="p-text-XbU-2">
                    <span class="span-lQH-1">
                      {{ deviceruninfo.sampleCount || "0" }}</span
                    >
                  </div>
                </div>
              </div>

              <div class="frame-JtK-11">
                <div class="text-XbU-2">
                  <div class="p-text-XbU-2">
                    <span class="span-lQH-1">
                      {{ deviceruninfo.storageStatus || "0.00" }}%</span
                    >
                  </div>
                </div>
              </div>
              <div class="frame-JtK-11">
                <div class="text-XbU-2">
                  <div class="p-text-XbU-2">
                    <span class="span-lQH-1">
                      {{ deviceruninfo.isOffline ? "离线" : "正常" }}</span
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </BorderBox10>
      </el-col>
      <el-col :span="10" style="height: 55vh" class="col-item">
        <div class="itemtitle1">试验场</div>

        <!-- <div class="itemtitlebottom"></div> -->
        <BorderBox10>
          <div ref="chinaMap" style="height: 100%; padding: 10px"></div>

          <span
            style="position: absolute; left: 20px; bottom: 10px"
            v-if="state.mapicdata.site"
          >
            <div
              style="
                color: #dc341f;
                border: 1px solid #333;
                width: 180px;
                font-weight: bold;
                font-size: 19px;
                margin-bottom: 10px;
                border-radius: 6px;
                line-height: 25px;
                background-color: rgba(51, 51, 51, 0.3);
                font-family: HarmonyOSSansSC-Medium;
              "
            >
              场地：{{ state.mappddata.site }}<br />
              地点：{{ state.mappddata.location }}<br />
              坐标：{{ state.mappddata.value && state.mappddata.value[1] }}
              <br />
              &emsp;&emsp;&emsp;{{
                state.mappddata.value && state.mappddata.value[0]
              }}
              <br />
              高度：{{ state.mappddata.height }}<br />
            </div>
          </span>

          <!-- 右侧显示IC类型设备 -->
          <span
            style="position: absolute; right: 20px; bottom: 10px"
            v-if="state.mapicdata.site"
          >
            <div
              style="
                color: #dc341f;
                font-weight: bold;
                border: 1px solid #333;
                width: 180px;
                font-size: 19px;
                margin-bottom: 10px;
                border-radius: 6px;
                line-height: 25px;
                background-color: rgba(51, 51, 51, 0.3);
                font-family: HarmonyOSSansSC-Medium;
              "
            >
              场地：{{ state.mapicdata.site }}<br />
              地点：{{ state.mapicdata.location }}<br />
              坐标：{{ state.mapicdata.value && state.mapicdata.value[1] }}
              <br />
              &emsp;&emsp;&emsp;{{
                state.mapicdata.value && state.mapicdata.value[0]
              }}
              <br />
              高度：{{ state.mapicdata.height }}<br />
            </div>
          </span>
        </BorderBox10>
      </el-col>
      <el-col :span="7" style="height: 55vh" class="col-item">
        <div class="itemtitle1">器件统计</div>
        <!-- <div class="itemtitlebottom"></div> -->
        <BorderBox10>
          <!-- <div class="iteminfo" style="height: 57vh"> -->
          <el-row :gutter="12" style="padding: 4vh 10px 0 10px">
            <el-col :span="8" class="item-col1">
              <img class="item-img1" src="@/assets/images/index/ypzl.png" />
              <div class="item-text1">
                <div class="item-label">测试容量</div>
                <span
                  class="item-value"
                  :style="{ color: norderstatusColorMap['正常'] }"
                  >{{ state.componentcount.testCount }}</span
                >
              </div>
            </el-col>
            <el-col :span="8" class="item-col1" style="text-align: center">
              <img class="item-img1" src="@/assets/images/index/fz.png" />
              <div class="item-text1">
                <div class="item-label">翻转次数</div>
                <span
                  class="item-value"
                  :style="{ color: norderstatusColorMap['翻转'] }"
                  >{{ formatValue(state.componentcount.fzcount) }}</span
                >
              </div>
            </el-col>

            <el-col :span="8" class="item-col1">
              <img class="item-img1" src="@/assets/images/index/bram.png" />
              <div class="item-text1">
                <div class="item-label">闩锁次数</div>
                <span
                  class="item-value"
                  :style="{ color: norderstatusColorMap['闩锁'] }"
                  >{{ formatValue(state.componentcount.sscount) }}</span
                >
              </div>
            </el-col>
            <el-col :span="8" class="item-col1">
              <img class="item-img1" src="@/assets/images/index/ypsl.png" />
              <div class="item-text1">
                <div class="item-label">样品数量</div>
                <span
                  class="item-value"
                  :style="{ color: norderstatusColorMap['正常'] }"
                  >{{ formatValue(state.componentcount.ypsl) }}</span
                >
              </div>
            </el-col>
            <el-col :span="8" class="item-col1">
              <img class="item-img1" src="@/assets/images/index/csdy.png" />
              <div class="item-text1">
                <div class="item-label">测试电压</div>
                <span
                  class="item-value"
                  :style="{ color: norderstatusColorMap['正常'] }"
                  >{{ state.componentcount.testVoltage }}V</span
                >
              </div>
            </el-col>
            <el-col :span="8" class="item-col1">
              <img class="item-img1" src="@/assets/images/index/shzl.png" />
              <div class="item-text1">
                <div class="item-label">烧毁数量</div>
                <span
                  class="item-value"
                  :style="{ color: norderstatusColorMap['烧毁'] }"
                  >{{ formatValue(state.componentcount.shsl) }}</span
                >
              </div>
            </el-col>
          </el-row>
          <!-- </div> -->
        </BorderBox10>
      </el-col>

      <el-col :span="12" style="height: 34vh" class="col-item">
        <div class="itemtitle1">测试板状态</div>
        <!-- <div class="itemtitlebottom"></div> -->
        <BorderBox10>
          <!-- <div class="iteminfo" style="height: 27vh"> -->
          <div class="frame-JWQ-3" style="margin-left: 10px">
            <span
              class="frame-Sbq-1"
              style="display: flex; align-items: flex-end"
            >
              <span
                class="vec-rectangle-mnV-1"
                :style="{
                  background: getColorByStatus('正常'),
                  border: getBorderByStatus('正常'),
                }"
              ></span>
              <span style="margin-left: 10px">正常</span>
            </span>
            <span
              class="frame-Sbq-1"
              style="display: flex; align-items: flex-end"
            >
              <span
                class="vec-rectangle-mnV-1"
                :style="{
                  background: getColorByStatus('断电'),
                  border: getBorderByStatus('断电'),
                }"
              ></span>
              <span style="margin-left: 10px">断电</span>
            </span>
            <span
              class="frame-Sbq-1"
              style="display: flex; align-items: flex-end"
            >
              <span
                class="vec-rectangle-mnV-1"
                :style="{
                  background: getColorByStatus('闩锁'),
                  border: getBorderByStatus('闩锁'),
                }"
              ></span>
              <span style="margin-left: 10px">闩锁</span>
            </span>
            <span
              class="frame-Sbq-1"
              style="display: flex; align-items: flex-end"
            >
              <span
                class="vec-rectangle-mnV-1"
                :style="{
                  background: getColorByStatus('翻转'),
                  border: getBorderByStatus('翻转'),
                }"
              ></span>
              <span style="margin-left: 10px">翻转</span>
            </span>
            <span
              class="frame-Sbq-1"
              style="display: flex; align-items: flex-end"
            >
              <span
                class="vec-rectangle-mnV-1"
                :style="{
                  background: getColorByStatus('烧毁'),
                  border: getBorderByStatus('烧毁'),
                }"
              ></span>
              <span style="margin-left: 10px">烧毁</span>
            </span>
            <span
              class="frame-Sbq-1"
              style="display: flex; align-items: flex-end"
            >
              <span
                class="vec-rectangle-mnV-1"
                :style="{
                  background: getColorByStatus('退化'),
                  border: getBorderByStatus('退化'),
                }"
              ></span>
              <span style="margin-left: 10px">退化</span>
            </span>
          </div>
          <el-divider style="margin: 10px; width: 98%" />
          <div
            style="
              width: 100%;
              display: flex;
              justify-content: space-between;
              height: 26vh;
              padding: 0.5vh 0.4vw;
            "
          >
            <!-- 第一个容器 - 2列布局 -->
            <div
              style="
                width: 13.5vw;
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 0.5vw;
              "
            >
              <div
                v-for="(row, rowIndex) in state.componentICStatus"
                :key="rowIndex"
                :style="{
                  background: getColorByStatus(row.status),
                  height: '3vh',
                  borderRadius: '2px',
                  border: getBorderByStatus(row.status),
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#fff',
                  fontSize: 'clamp(10px, 1.5vh, 14px)',
                }"
                :title="`${row.devicename}: ${row.status}`"
              >
                {{ row.value }}
              </div>
            </div>

            <!-- 第二个容器 - 2列布局 -->
            <div
              style="
                width: 13.5vw;
                display: grid;
                grid-template-columns: repeat(2, 1fr);
                gap: 0.5vw;
              "
            >
              <div
                v-for="(row, rowIndex) in state.componentIC1Status"
                :key="rowIndex"
                :style="{
                  background: getColorByStatus(row.status),
                  height: '3vh',
                  borderRadius: '2px',
                  border: getBorderByStatus(row.status),
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#fff',
                  fontSize: 'clamp(10px, 1.5vh, 14px)',
                }"
                :title="`${row.devicename}: ${row.status}`"
              >
                {{ row.value }}
              </div>
            </div>

            <!-- 第三个容器 - 3列布局 -->
            <div
              style="
                width: 21vw;
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 0.5vw;
              "
            >
              <div
                v-for="(row, rowIndex) in state.componentPDStatus"
                :key="rowIndex"
                :style="{
                  background: getColorByStatus(row.status),
                  height: '3vh',
                  borderRadius: '2px',
                  border: getBorderByStatus(row.status),
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: '#fff',
                  fontSize: 'clamp(10px, 1.5vh, 14px)',
                }"
                :title="`${row.devicename}: ${row.status}`"
              >
                {{ state.componentcount.testVoltage + "V" }}
              </div>
            </div>
          </div>
        </BorderBox10>
      </el-col>

      <el-col :span="12" style="height: 34vh" class="col-item">
        <div class="itemtitle1">失效时间分布</div>
        <!-- <div class="itemtitlebottom"></div> -->
        <BorderBox10>
          <!-- <div class="iteminfo" style="padding-bottom: 0px"> -->
          <div
            ref="lineChart"
            class="chart-container"
            style="height: 100%"
          ></div>
          <!-- </div> -->
        </BorderBox10>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import {
  ref,
  onMounted,
  onUnmounted,
  nextTick,
  reactive,
  watch,
  getCurrentInstance,
} from "vue";
import * as echarts from "echarts";
// 引入中国地图数据
import chinaJson from "@/assets/json/chinafull.json";

import {
  getDeviceInfoAndRunInfo,
  getBoardStatus,
  getLastsixmonth,
} from "@/api/device/dashboard";

import Screenfull from "@/components/Screenfull";
import { formatLargeNumber } from "@/utils/index";
import { BorderBox10, Decoration7 } from "@kjgl77/datav-vue3";
import "@/assets/styles/index.css";
echarts.registerMap("china", chinaJson);
const { proxy } = getCurrentInstance();
// 定义图表容器的 ref
const barChart = ref(null);
const lineChart = ref(null);
const pieChart = ref(null);
const chinaMap = ref(null);
const getDeviceIconPath = (type) => {
  // 根据设备类型返回对应的图标路
  return "@/assets/images/index/" + type + ".png";
};
// 省会城市数据
const provincialCities = [
  { name: "哈尔滨", value: [126.63, 45.75] },
  { name: "长春", value: [125.35, 43.88] },
  { name: "沈阳", value: [123.43, 41.8] },
  { name: "呼和浩特", value: [111.65, 40.82] },
  { name: "石家庄", value: [114.48, 38.03] },
  { name: "太原", value: [112.53, 37.87] },
  { name: "济南", value: [117, 36.65] },
  { name: "郑州", value: [113.65, 34.76] },
  { name: "西安", value: [108.95, 34.27] },
  { name: "兰州", value: [103.73, 36.03] },
  { name: "西宁", value: [101.74, 36.56] },
  { name: "乌鲁木齐", value: [87.68, 43.77] },
  { name: "成都", value: [104.06, 30.57] },
  { name: "武汉", value: [114.31, 30.52] },
  { name: "长沙", value: [113, 28.21] },
  { name: "南京", value: [118.76, 32.04] },
  { name: "合肥", value: [117.27, 31.86] },
  { name: "杭州", value: [120.19, 30.26] },
  { name: "南昌", value: [115.89, 28.68] },
  { name: "福州", value: [119.3, 26.08] },
  { name: "广州", value: [113.23, 23.16] },
  { name: "南宁", value: [108.33, 22.84] },
  { name: "昆明", value: [102.73, 25.04] },
  { name: "贵阳", value: [106.71, 26.57] },
  { name: "海口", value: [110.35, 20.02] },
  { name: "台北", value: [121.5, 25.03] },
  { name: "香港", value: [114.1, 22.3] },
  { name: "澳门", value: [113.54, 22.19] },
  { name: "北京", value: [116.46, 39.92] },
  { name: "上海", value: [121.48, 31.22] },
  { name: "天津", value: [117.2, 39.13] },
  { name: "重庆", value: [106.54, 29.59] },
  { name: "拉萨", value: [91.11, 29.97] },
];
const props = defineProps({
  deviceinfo: {
    type: Object,
    default: { type: "ic", datasourceindex: "" },
  },
});
const state = reactive({
  deviceruninfos: [],
  componentcount: {
    //器件统计
    testCount: "27.87Gb", //测试数量
    fzcount: 0, //翻转次数
    sscount: 0, //闩锁次数
    ypsl: 1080, //样品数量
    testVoltage: 0, // 测试电压
    shsl: 0, //烧毁数量
  },
  devicecount: {
    totalDevices: 0,
    statusCnt1: 0,
    statusCnt2: 0,
    statusCnt3: 0,
    statusCnt4: 0,
    totalDevices: 0,
  },
  mapicdata: {},
  mappddata: {},
  mapdata: [],
  deviceList: [],
  lastweekCount: [],
  componentStatus: [],
  componentICStatus: [],
  componentIC1Status: [],
  componentPDStatus: [],
});
const alarmEvents = ref([]);
const formatValue = (value) => {
  if (value >= 10000) {
    return (value / 1000).toFixed(2) + "K";
  } else {
    return value;
  }
};
/**
 * 将度分格式字符串转换为十进制度数值（地理坐标系）
 * @param {string} dmsStr - 度分格式的字符串，如"90°33'"、"-90°33'"、"东经 90°33'"、"90°33'"
 * @returns {number} 十进制度格式的数值
 */
function dmsToDecimal(dmsStr) {
  if (!dmsStr || typeof dmsStr !== "string") {
    return null;
  }

  const cleanStr = dmsStr.replace(/\s+/g, "");
  let sign = 1;
  let numericPart = cleanStr;

  if (cleanStr.startsWith("-")) {
    sign = -1;
    numericPart = cleanStr.substring(1);
  } else if (cleanStr.includes("南纬") || cleanStr.includes("西经")) {
    sign = -1;
    numericPart = cleanStr.replace("南纬", "").replace("西经", "");
  } else if (cleanStr.includes("北纬") || cleanStr.includes("东经")) {
    numericPart = cleanStr.replace("北纬", "").replace("东经", "");
  }

  const match = numericPart.match(/(\d+(?:\.\d+)?)°(\d+(?:\.\d+)?)'/);
  if (!match) return null;

  const [, degrees, minutes] = match;
  return sign * (parseFloat(degrees) + parseFloat(minutes) / 60);
}
// 初始化折线图的函数
const initLineChart = () => {
  if (!lineChart.value) return;
  const lineChartInstance = echarts.init(lineChart.value);
  const lineOption = {
    grid: {
      bottom: 5,
      left: 80,
      right: 80,

      containLabel: true, // 确保标签不被剪切
    },
    xAxis: {
      type: "category",
      data: state.lastweekCount.map((item) => {
        const date = new Date(item.time);
        return `${String(date.getFullYear()).padStart(4, "0")}-${String(
          date.getMonth() + 1
        ).padStart(2, "0")}`;
      }),
      axisLabel: {
        color: "#ffffff", // 设置 x 轴文字颜色为白色
        fontSize: 20, // 放大字体大小
      },
      axisLine: {
        lineStyle: {
          color: "#ffffff",
        },
      },
      name: "",
      nameTextStyle: {
        color: "#ffffff",
        fontSize: 20, // 放大坐标轴名称字体
      },
    },
    yAxis: [
      {
        type: "value",
        name: "翻转次数",
        minInterval: 1,
        axisLabel: {
          color: "#ffffff",
          fontSize: 20,
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(255, 255, 255, 0.8)",
          },
        },
        splitLine: {
          lineStyle: {
            color: "rgba(255, 255, 255, 0.2)", // 降低横线亮度
          },
        },
        position: "left", // 左侧Y轴
        nameTextStyle: {
          color: "#ffffff",
          fontSize: 20, // 放大坐标轴名称字体
        },
      },
      {
        type: "value",
        name: "次数",
        minInterval: 1,
        axisLabel: {
          color: "#ffffff",
          fontSize: 20,
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(255, 255, 255, 0.8)",
          },
        },
        splitLine: {
          lineStyle: {
            color: "rgba(255, 255, 255, 0.2)", // 降低横线亮度
          },
        },
        position: "right", // 右侧Y轴
        nameTextStyle: {
          color: "#ffffff",
          fontSize: 20, // 放大坐标轴名称字体
        },
      },
    ],
    // 添加图例配置
    legend: {
      type: "plain", // 普通图例
      orient: "horizontal", // 水平布局
      right: "center", // 距离右侧 5% 的位置，可按需调整
      top: "2%", // 距离顶部 5% 的位置，可按需调整表顶部

      textStyle: {
        color: "#ffffff", // 图例文字颜色
        fontSize: 20, // 放大字体大小
      },
      // 自动从 series 中获取图例数据
      data: ["翻转", "闩锁", "烧毁", "退化"],
    },
    series: [
      {
        data:
          state.lastweekCount.length > 0
            ? state.lastweekCount.map((item) => item.闩锁 || 0)
            : [],
        type: "line",
        name: "闩锁",
        itemStyle: { color: norderstatusColorMap["闩锁"] },
        yAxisIndex: 1, // 使用左侧Y轴
        barWidth: "20%", // 设置柱状图宽度（可以根据需要调整这个百分比）
        label: {
          show: true,
          position: "top",
          color: "#ffffff",
          fontSize: 20, // 放大数据标签字体
          formatter: (params) => formatValue(params.value),
        },
      },
      {
        data:
          state.lastweekCount.length > 0
            ? state.lastweekCount.map((item) => item.翻转 || 0)
            : [],
        type: "bar",
        name: "翻转",
        itemStyle: { color: norderstatusColorMap["翻转"] },
        yAxisIndex: 0, // 使用右侧Y轴
        barWidth: "20%", // 设置柱状图宽度（可以根据需要调整这个百分比）
        smooth: true, // 曲线平滑
        smoothMonotone: "x", // 保证单调性
        symbol: "circle", // 数据点形状
        symbolSize: 8, // 数据点大小
        lineStyle: {
          width: 4, // 线条宽度
          shadowBlur: 10, // 阴影模糊
          shadowColor: norderstatusColorMap["翻转"], // 阴影颜色
          shadowOffsetX: 0,
          shadowOffsetY: 5,
        },
        emphasis: {
          focus: "series", // 高亮当前系列
          itemStyle: {
            borderWidth: 2,
            borderColor: "#fff",
          },
          lineStyle: {
            width: 6, // 悬停时线条变粗
          },
        },
        label: {
          show: true,
          position: "top",
          color: "#ffffff",
          fontSize: 20, // 放大数据标签字体
          formatter: (params) => formatValue(params.value),
        },
      },
      {
        data:
          state.lastweekCount.length > 0
            ? state.lastweekCount.map((item) => item.烧毁 || 0)
            : [],
        type: "line",
        name: "烧毁",
        itemStyle: { color: norderstatusColorMap["烧毁"] },
        yAxisIndex: 1,
        smooth: true, // 曲线平滑
        smoothMonotone: "x", // 保证单调性
        symbol: "circle", // 数据点形状
        symbolSize: 8, // 数据点大小
        lineStyle: {
          width: 4, // 线条宽度
          shadowBlur: 10, // 阴影模糊
          shadowColor: norderstatusColorMap["烧毁"], // 阴影颜色
          shadowOffsetX: 0,
          shadowOffsetY: 5,
        },
        emphasis: {
          focus: "series", // 高亮当前系列
          itemStyle: {
            borderWidth: 2,
            borderColor: "#fff",
          },
          lineStyle: {
            width: 6, // 悬停时线条变粗
          },
        },
        label: {
          show: true,
          position: "top",
          color: "#ffffff",
          fontSize: 15, // 放大数据标签字体
          formatter: (params) => formatValue(params.value),
        },
      },
      {
        data:
          state.lastweekCount.length > 0
            ? state.lastweekCount.map((item) => item.退化 || 0)
            : [],
        type: "line",
        name: "退化",
        itemStyle: { color: norderstatusColorMap["退化"] },
        yAxisIndex: 1,
        smooth: true, // 曲线平滑
        smoothMonotone: "x", // 保证单调性
        symbol: "circle", // 数据点形状
        symbolSize: 8, // 数据点大小
        lineStyle: {
          width: 4, // 线条宽度
          shadowBlur: 10, // 阴影模糊
          shadowColor: norderstatusColorMap["退化"], // 阴影颜色
          shadowOffsetX: 0,
          shadowOffsetY: 5,
        },
        emphasis: {
          focus: "series", // 高亮当前系列
          itemStyle: {
            borderWidth: 2,
            borderColor: "#fff",
          },
          lineStyle: {
            width: 3, // 悬停时线条变粗
          },
        },
        label: {
          show: true,
          position: "top",
          color: "#ffffff",
          fontSize: 15, // 放大数据标签字体
          formatter: (params) => formatValue(params.value),
        },
      },
    ],
  };
  lineChartInstance.setOption(lineOption);
};

// 初始化中国地图的函数
const initChinaMap = () => {
  if (!chinaMap.value) return;
  const chinaMapInstance = echarts.init(chinaMap.value);

  const chinaMapOption = {
    grid: {
      right: 0,
      bottom: 0,
      left: 0,
      containLabel: true, // 确保标签不被剪切
    },
    // tooltip: {
    //   trigger: "item",
    //   backgroundColor: "none",
    //   borderColor: "#333",
    //   textStyle: {
    //     color: "#fff",
    //     fontSize: 25,
    //   },
    //   padding: 10,
    //   // formatter: function (params) {
    //   //   const data = params.data;
    //   //   return `
    //   //     设备名称：${data.devicename}<br/>
    //   //     场地：${data.name}<br/>
    //   //     坐标：${data.value[0].toFixed(2)}, ${data.value[1].toFixed(2)}<br/>
    //   //     描述：${data.remark}<br/>
    //   //     ${data.isOffline ? "状态：离线" : "状态：在线"}<br/>
    //   //     运行天数：${data.runDays}天<br/>
    //   //     存储状态：${data.storageStatus}%
    //   //   `;
    //   // },
    // },
    geo: {
      map: "china", // 使用中国地图，确保已经加载了中国地图的 JSON 数据
      label: {
        emphasis: {
          show: false,
        },
        normal: {
          show: true,
          color: "rgba(12, 209, 225, 1)",
          fontSize: 10,
        },
      },
      roam: false, // 是否允许缩放和平移漫游
      // 设置默认中心点和缩放比例
      center: [105, 35],
      zoom: 1.7,
      // 美化地图样式
      itemStyle: {
        normal: {
          areaColor: "#2c3e50", // 深灰色
          borderColor: "#009e8", // 边框颜色
        },
        emphasis: {
          areaColor: "#f47920", // 鼠标悬停时地图区域颜色
        },
      },
    },
    series: [
      {
        name: "设备分布",
        type: "effectScatter",
        coordinateSystem: "geo",
        // type: "scatter", // 使用散点图类型来标记点
        // coordinateSystem: "geo", // 指定使用地理坐标系
        data: state.mapdata,
        // symbol: `image://${
        //   new URL("@/assets/images/index/dingwei.gif", import.meta.url).href
        // }`,
        // symbol: "arrow",
        symbolSize: function (val) {
          return 15;
        },
        rippleEffect: {
          //涟漪特效
          period: 4, //动画时间，值越小速度越快
          brushType: "stroke", //波纹绘制方式 stroke, fill
          scale: 4, //波纹圆环最大限制，值越大波纹越大
          opacity: 0.6,
        },
        // symbolOffset: [0, -25], // 调整偏移，使尖端对准坐标点
        itemStyle: {
          normal: {
            color: "red",
          },
          emphasis: {
            color: "#ffcc00", // 鼠标悬停时的颜色
            shadowBlur: 10,
            shadowColor: "#ffcc00",
          },
        },
        label: {
          normal: {
            formatter: "{b}", // 显示点的名称
            position: "top",
            show: true,
            textStyle: {
              color: "#ffffff",
              fontSize: 20,
              fontWeight: "bold",
            },
          },
          emphasis: {
            show: true,
            textStyle: {
              color: "#ffcc00",
              fontSize: 24,
              fontWeight: "bold",
            },
          },
        },
        // 添加动画效果
        // animationDelay: function (idx) {
        //   return idx * 300;
        // },
        // animationEasing: "elasticOut",
      },
      // {
      //   name: "省会",
      //   type: "scatter",
      //   coordinateSystem: "geo",
      //   data: provincialCities,
      //   symbolSize: 8,
      //   tooltip: {
      //     show: false,
      //     trigger: "item",
      //     formatter: "{b}", // 只显示名称
      //   },
      //   label: {
      //     show: false,
      //     normal: {
      //       formatter: "{b}", // 显示点的名称
      //       position: "right",
      //       fontSize: 10,
      //       show: true,
      //       textStyle: {
      //         color: "#ffffff",
      //       },
      //     },
      //     emphasis: {
      //       show: true,
      //       fontSize: 10,
      //       textStyle: {
      //         color: "#ffcc00",
      //       },
      //     },
      //   },
      //   itemStyle: {
      //     color: "#ff0000",
      //   },
      // },
    ],
  };

  chinaMapInstance.setOption(chinaMapOption);
};
// 定义状态和颜色的映射
const statusColorMap = {
  正常: "rgba(59, 179, 70, 0.6)",
  断电: "rgba(158, 158, 158, 0.7)",
  闩锁: "rgba(249, 57, 32, 0.7)",
  BRAM翻转: "rgba(252, 136, 0, 0.7)",
  CRAM翻转: "rgba(255, 235, 59, 0.7)",
  烧毁: "rgba(198, 40, 40, 0.7)",
  退化: "rgba(156, 39, 176, 0.7)",
  翻转: "rgba(252, 136, 0, 0.7)",
};
const norderstatusColorMap = {
  正常: "rgba(59, 179, 70)",
  断电: "rgba(158, 158, 158)",
  闩锁: "rgba(249, 57, 32)",
  BRAM翻转: "rgba(252, 136, 0)",
  CRAM翻转: "rgba(255, 235, 59)",
  烧毁: "rgba(198, 40, 40)",
  退化: "rgba(156, 39, 176)",
  翻转: "rgba(252, 136, 0)",
};
// 根据状态获取颜色
const getColorByStatus = (status) => {
  return statusColorMap[status] || "transparent";
};

// 根据状态获取 border
const getBorderByStatus = (status) => {
  return `${norderstatusColorMap[status]} 1px solid` || "transparent";
};
// 定义时间、日期和星期的 ref
const currentTime = ref("");
const currentDate = ref("");
const currentDay = ref("");

let timer;

// 更新时间的函数
const updateTime = () => {
  const date = new Date();
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");
  const seconds = String(date.getSeconds()).padStart(2, "0");
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const days = [
    "星期日",
    "星期一",
    "星期二",
    "星期三",
    "星期四",
    "星期五",
    "星期六",
  ];

  currentTime.value = `${hours}:${minutes}:${seconds}`;
  currentDate.value = `${year}-${month}-${day}`;
  currentDay.value = days[date.getDay()];
};

// 添加窗口大小变化处理函数
const handleResize = () => {
  // 延迟执行，避免频繁触发
  setTimeout(() => {
    // 检查图表实例是否存在，存在则调用resize方法
    if (lineChart.value) {
      echarts.getInstanceByDom(lineChart.value)?.resize();
    }
    if (chinaMap.value) {
      echarts.getInstanceByDom(chinaMap.value)?.resize();
    }
  }, 100);
};

// 定义数据获取函数
const fetchData = () => {
  getLastsixmonth().then((res) => {
    // state.lastweekCount = res;
    let lastweekCount = [];

    res.forEach((item) => {
      for (let i = 0; i < item.statusaccountingList.length; i++) {
        if (!lastweekCount[i]) {
          lastweekCount[i] = {
            time: item.statusaccountingList[i].time,
            烧毁: 0,
            翻转: 0,
            退化: 0,
            闩锁: 0,
          };
        }
        // 根据类型累加数据
        if (item.type == "ic") {
          lastweekCount[i].翻转 += item.statusaccountingList[i].statusCnt3 || 0;
          lastweekCount[i].翻转 += item.statusaccountingList[i].statusCnt4 || 0;
          lastweekCount[i].闩锁 += item.statusaccountingList[i].statusCnt2 || 0;
        } else {
          lastweekCount[i].烧毁 += item.statusaccountingList[i].statusCnt1 || 0;
          lastweekCount[i].退化 += item.statusaccountingList[i].statusCnt2 || 0;
        }
      }

      // 遍历statusaccountingList数组，提取每个对象中的time和statusCnt1
    });
    // console.log(lastweekCount);
    state.lastweekCount = lastweekCount;
    nextTick(() => {
      initLineChart();
    });
  });
  getBoardStatus().then((res) => {
    let icdatalist = [];
    let icdatalist1 = [];
    let pddatalist = [];
    for (let item of res) {
      if (item.type == "ic") {
        let boardTypeMap = {};
        item.types.forEach((item) => {
          boardTypeMap[item.boardNumber] = item.boardType;
        });
        for (let i = 0; i < 12; i++) {
          if (item.datasourceindex == "1") {
            icdatalist1.push({
              devicename: item.name,
              type: item.type,
              topic: item.topic,
              value: boardTypeMap[i + 1] == "三路电" ? "22nm" : "55nm",
              boardtype: boardTypeMap[i + 1] == "三路电" ? 3 : 2,
              status: item[`b${i + 1}`],
            });
          } else {
            icdatalist.push({
              devicename: item.name,
              type: item.type,
              topic: item.topic,
              value: boardTypeMap[i + 1] == "三路电" ? "22nm" : "55nm",
              boardtype: boardTypeMap[i + 1] == "三路电" ? 3 : 2,
              status: item[`b${i + 1}`],
            });
          }
        }
      } else {
        for (let i = 0; i < 18; i++) {
          pddatalist.push({
            devicename: item.name,
            type: item.type,
            topic: item.topic,
            status: item[`b${i + 1}`],
          });
        }
      }
    }
    state.componentICStatus = icdatalist.sort(
      (a, b) => b.boardtype - a.boardtype
    );
    state.componentIC1Status = icdatalist1.sort(
      (a, b) => b.boardtype - a.boardtype
    );
    state.componentPDStatus = pddatalist;
  });
  getDeviceInfoAndRunInfo().then((res) => {
    let mapdata = [];
    let deviceruninfos = [];
    state.componentcount.sscount = 0;
    res.forEach((element) => {
      // 一种类型设备只取第一个的信息进行展示
      if (element.datasourceindex == "") {
        mapdata.push({
          name: element.location,
          location: element.location,
          height: element.height,
          value: [dmsToDecimal(element.lng), dmsToDecimal(element.lat)],
        });
      }
      // mapdata.push({
      //   name: element.location,
      //   location: element.location,
      //   height: element.height,
      //   value: [dmsToDecimal(element.lng), dmsToDecimal(element.lat)],
      // });
      deviceruninfos.push({
        devicename: element.devicename,
        type: element.type,
        topic: element.topic,
        name: element.name,
        value: [element.lng, element.lat],
        remark: element.remark,
        runDays: element.runDays,
        storageStatus: element.storageStatus,
        sampleCount: element.dataLastIc ? element.dataLastIc.totalDevices : 0,
        isOffline: element.isOffline,
      });
      if (element.type === "ic") {
        state.mapicdata = {
          site: element.site,
          location: element.location,
          height: element.height,
          value: [element.lng, element.lat],
        };

        state.componentcount.fzcount += element.dataLastIc
          ? element.dataLastIc.statusCnt3
          : 0;
        state.componentcount.fzcount += element.dataLastIc
          ? element.dataLastIc.statusCnt4
          : 0;
        state.componentcount.sscount += element.dataLastIc
          ? element.dataLastIc.statusCnt2
          : 0;
        state.componentcount.testCount = element.samplecount || 0;
      } else {
        state.mappddata = {
          site: element.site,
          location: element.location,
          height: element.height,
          value: [element.lng, element.lat],
        };
        state.componentcount.ypsl = element.dataLastIc
          ? element.dataLastIc.totalDevices
          : 0;
        state.componentcount.shsl = element.dataLastIc
          ? element.dataLastIc.statusCnt1
          : 0;
        state.componentcount.testVoltage = element.systemvoltage || 0;
      }
    });
    state.mapdata = mapdata;
    state.deviceruninfos = deviceruninfos;

    nextTick(() => {
      initChinaMap();
    });
  });
};

let dataTimer; // 数据定时器

onMounted(() => {
  // 初始化时间
  // 添加空值检查，避免访问undefined的属性
  fetchData();
  // 生成模拟数据
  // generateMockData();
  dataTimer = setInterval(fetchData, 300000);
  updateTime();
  // 每秒更新一次时间
  timer = setInterval(updateTime, 1000);
  // // 添加窗口大小变化监听
  window.addEventListener("resize", handleResize);

  // // 初始加载时触发一次resize确保图表正确显示
  nextTick(() => {
    handleResize();
  });
});
onUnmounted(() => {
  // 组件卸载时清除定时器
  clearInterval(dataTimer);
  clearInterval(timer);
});
// watch(
//   () => props.deviceinfo,
//   (newval) => {
//     // 修复拼写错误：devceinfo -> deviceinfo
//     if (newval) {
//       fetchData();
//       clearInterval(dataTimer);
//       dataTimer = setInterval(fetchData, 300000);
//     }
//   }
// );
</script>

<style scoped>
#app {
  overflow-y: hidden;
}
/* 全局容器样式 */
.scroll-container1 {
  background-color: royalblue;
  width: 100%;
  height: 100%;
  background-image: url("@/assets/images/index/indexbg.png");
  mix-blend-mode: overlay;
  background-size: 100% 100%;

  mix-blend-mode: normal;

  color: white;
}
.header {
  height: 9vh;
  padding: 0px;
}
.dv-border-box-10 {
  height: 93%;
}
.site-title {
  position: absolute;
  top: 20px;
  left: 30px;
  width: 130px;

  color: rgba(12, 209, 225, 1);
  font-size: 25px;
  font-weight: 700;
  font-family: "HarmonyOSSansSC-Bold";
  white-space: nowrap;
}

.main-title {
  width: 800px;
  margin: 0 auto;
  margin-top: 10px;
  text-align: center;
}

.top-title {
  font-size: 40px;
  font-weight: 700;
  background-image: linear-gradient(
    180deg,
    rgba(255, 255, 255, 1) 0%,
    rgba(145, 251, 255, 1) 100%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  display: inline-block;
}

.weather-time-container {
  position: absolute;
  top: 20px;
  right: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 500px;
  color: rgba(12, 209, 225, 1);
  font-size: 28px;
  font-weight: 700;
  gap: 10px;
}

/* 删除未使用的.decoration样式 */
.item-col1 {
  text-align: center;
  height: 23vh;
}
.item-text1 {
  text-align: center;
}

.item-value {
  margin-top: 10px;
  color: rgba(80, 212, 217, 1);
  font-size: 35px;
  font-weight: 700;
  font-family: "HarmonyOSSansSC-Bold";
  letter-spacing: 0px;
  white-space: nowrap;
}
.chart-container {
  width: 100%;
  height: 21vh;
}

/* 删除未使用的.main-content样式 */

.frame-JWQ-3 {
  width: auto;
  display: flex;
  margin-bottom: 5px;
  height: auto;
  mix-blend-mode: normal;
  justify-content: flex-start;
  align-items: flex-start;
  font-size: 28px;
  gap: 34px;
  row-gap: 34px;
  column-gap: 34px;
}
.vec-rectangle-mnV-1 {
  width: 28px;
  height: 28px;
  border-radius: 2px;
  mix-blend-mode: normal;
  display: flex;
  box-sizing: border-box;
  opacity: 1;
  background: rgba(59, 179, 70, 0.4);
  border: rgba(59, 179, 70) 1px solid;
  order: 0;
  flex-shrink: 0;
}
.vec-rectangle-mnV-2 {
  width: 28px;
  height: 28px;
  border-radius: 2px;
  mix-blend-mode: normal;
  display: flex;
  box-sizing: border-box;
  opacity: 1;
  background: rgba(252, 136, 0, 0.4);
  border: rgba(252, 136, 0) 1px solid;
  order: 0;
  flex-shrink: 0;
}
.vec-rectangle-mnV-3 {
  width: 28px;
  height: 28px;
  border-radius: 2px;
  mix-blend-mode: normal;
  display: flex;
  box-sizing: border-box;
  opacity: 1;
  background: rgba(249, 57, 32, 0.4);
  border: rgba(249, 57, 32) 1px solid;
  order: 0;
  flex-shrink: 0;
}
.vec-rectangle-mnV-5 {
  width: 28px;
  height: 28px;
  border-radius: 2px;
  mix-blend-mode: normal;
  display: flex;
  box-sizing: border-box;
  opacity: 1;
  background: rgba(255, 235, 59, 0.4);
  border: rgba(255, 235, 59) 1px solid;
  order: 0;
  flex-shrink: 0;
}
/* 添加第六个状态样式 */
.vec-rectangle-mnV-6 {
  width: 28px;
  height: 28px;
  border-radius: 2px;
  mix-blend-mode: normal;
  display: flex;
  box-sizing: border-box;
  opacity: 1;
  background: rgba(158, 158, 158, 0.4);
  border: rgba(158, 158, 158) 1px solid;
  order: 0;
  flex-shrink: 0;
}
.frame-Sbq-1 span {
  /* 允许单词内换行，防止内容溢出 */
  word-break: break-all;
  /* 文本溢出容器时自动换行 */
  white-space: normal;
}

/* 删除未使用的.frame-IxF-35样式 */
/* 删除未使用的.text-sPe-1样式 */

/* 删除未使用的.frame-JTP-2、.frame-XRd-3、.frame-rig-4样式 */
/* 删除未使用的.frame-dDX-2样式 */

.text-EFD-1 {
  display: flex;
  flex-direction: column;
  z-index: 0;
  justify-content: start;
  height: 25px;
  mix-blend-mode: normal;
  color: rgba(255, 255, 255, 0.85);
  letter-spacing: -0.008999994920136839px;
  font-size: 23px;
  line-height: 28px;
  font-weight: 700;
  opacity: 1;
  font-family: "HarmonyOSSansSC-Medium";
  white-space: pre-wrap;
  order: 0;
  flex-shrink: 0;
}
.p-text-EFD-1 {
  display: inline;
  margin: 0px;
  width: 100%;
  text-align: center;
}
.text-XbU-2 {
  display: flex;
  flex-direction: column;
  z-index: 1;
  justify-content: start;
  height: auto;
  mix-blend-mode: normal;
  color: rgba(80, 212, 217, 1);
  font-size: 30px;
  font-weight: 700;
  opacity: 1;
  font-family: "HarmonyOSSansSC-Bold";
  letter-spacing: 0px;
  white-space: nowrap;
  order: 1;
  min-height: 29px;
}

.text-KuT-2 {
  display: flex;
  flex-direction: column;
  z-index: 1;
  justify-content: start;
  height: 19px;
  mix-blend-mode: normal;
  color: rgba(59, 179, 70, 1);
  letter-spacing: -0.008999994920136839px;
  font-size: 18px;
  line-height: 18px;
  font-weight: 700;
  opacity: 1;
  font-family: "HarmonyOSSansSC-Bold";
  white-space: pre-wrap;
  order: 1;
  flex-shrink: 0;
}
.text-MZK-1 {
  display: flex;
  flex-direction: column;
  z-index: 0;
  justify-content: start;

  height: 18px;
  mix-blend-mode: normal;
  color: rgba(255, 255, 255, 0.4);
  letter-spacing: -0.008999994920136839px;
  font-size: 16px;
  line-height: 18px;
  font-weight: 500;
  opacity: 1;
  font-family: "HarmonyOSSansSC-Medium";
  white-space: pre-wrap;
}
.img-QZp-1 {
  border: unset !important;
  box-shadow: unset;
  width: 24px;
  height: 24px;
  mix-blend-mode: normal;
  display: flex;
  background: url("@/assets/images/index/warn.png");
  order: 0;
  flex-shrink: 0;
}
.site-icon {
  display: inline-block;
  margin-right: 10px;

  background-image: url("@/assets/images/index/image.png");
  background-size: 100% 100%;
}
.dateimg {
  display: inline-block;
  margin-right: 10px;
  width: 40px;
  height: 40px;
  background-image: url("@/assets/images/index/date.png");
  background-size: 100% 100%;
}

/* 报警事件轮播样式 */
.seamless-warp {
  height: 25vh;
  overflow: hidden;
}
.capacity-info {
  display: flex;
  justify-content: space-around;
  align-items: center;
  height: 10vh;
  padding: 0;
}

.capacity-item {
  display: flex;
  align-items: center;
  gap: 15px;
}

.capacity-icon {
  /* border-radius: 50%; */
  display: flex;
  align-items: center;
  justify-content: center;
}

.bram-icon {
  background-color: rgba(252, 136, 0, 0.4);
  border: 1px solid rgba(252, 136, 0);
  background-image: url("@/assets/images/index/bram.png");
  background-size: 60% 60%;
  background-repeat: no-repeat;
  background-position: center;
}

.cram-icon {
  background-color: rgba(255, 235, 59, 0.4);
  border: 1px solid rgba(255, 235, 59);
  background-image: url("@/assets/images/index/cram.png");
  background-size: 60% 60%;
  background-repeat: no-repeat;
  background-position: center;
}

.capacity-text {
  display: flex;
  flex-direction: column;
}

.capacity-label {
  color: rgba(255, 255, 255, 0.85);
  font-size: 14px;
}

.capacity-value {
  color: rgba(80, 212, 217, 1);
  font-size: 20px;
  font-weight: 700;
}
.contetn_left-top {
  width: 25vw;
  height: 60vh;
}
.span-lQH-1 {
  line-height: 10vh;
  font-size: 28px;
  font-weight: 700;
  color: rgba(255, 255, 255, 1);
  font-family: "HarmonyOSSansSC-Bold";
}
.itemtitle1 {
  background: url("@/assets/images/index/itemtitlebg.png");
  background-size: 100% 100%;
  padding: 5px 40px;
  font-size: 28px;
  line-height: 30px;
  font-weight: 700;
}
.col-item {
  background: url("@/assets/images/index/center_map.png");
  background-size: 100% 100%;
}
.item-img1 {
  width: 12vh !important;
  height: 12vh !important;
  margin: auto;
}
div .item-label {
  color: rgba(255, 255, 255, 0.85);
  letter-spacing: -0.009px;
  font-size: 26px;
  line-height: 28px;
  margin: 10px;
  font-weight: 500;
  font-family: "HarmonyOSSansSC-Medium";
  white-space: pre-wrap;
}
.frame-jHS-3 {
  background: none;
  padding: 0 20px;
}
</style>
